package com.wbw.ssb.service.impl;

import com.wbw.ssb.dto.GranaryDto;
import com.wbw.ssb.mbg.entity.Granary;
import com.wbw.ssb.mbg.mapper.*;
import com.wbw.ssb.service.GranaryService;
import com.wbw.ssb.service.HumidityService;
import com.wbw.ssb.service.SmogService;
import com.wbw.ssb.service.TemperatureService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * @Author: guibo
 * @Description:
 * @Date: Created in 14:42 2021/5/25
 * @Modified By:
 */
@Service
public class GranaryServiceImpl implements GranaryService {
    @Autowired
    GranaryMapper granaryMapper;
    @Autowired
    HumidityService humidityService;
    @Autowired
    SmogService smogService;
    @Autowired
    TemperatureService temperatureService;

    @Override
    public int add(Granary granary) {
        return granaryMapper.insert(granary);
    }

    @Override
    public int delete(List<Long> ids) {
        return granaryMapper.delete(c->c.where(GranaryDynamicSqlSupport.id,isIn(ids)));
    }

    @Override
    public int update(Granary granary) {
        return granaryMapper.updateByPrimaryKeySelective(granary);
    }

    @Override
    public List<GranaryDto> list(Granary granary) {
        List<Granary> granaryList;
        List<GranaryDto> granaryDtoList = new ArrayList<>();
        if(granary==null){
            granaryList = granaryMapper.select(c->c);
        }else {
            granaryList = granaryMapper.select(c -> c
                    .where(GranaryDynamicSqlSupport.id, isEqualToWhenPresent(granary.getId()))
                    .and(GranaryDynamicSqlSupport.number,isEqualToWhenPresent(granary.getNumber()))
                    .and(GranaryDynamicSqlSupport.name, isLikeWhenPresent(granary.getName()).then(s -> "%" + s + "%"))
                    .and(GranaryDynamicSqlSupport.status, isEqualToWhenPresent(granary.getStatus()))
                    .orderBy(GranaryDynamicSqlSupport.id.descending())
            );
        }
        granaryList.forEach(c->{
            GranaryDto granaryDto = new GranaryDto();
            BeanUtils.copyProperties(c,granaryDto);
            granaryDto.setHumidity(humidityService.getNow(c.getNumber()).getHumidity());
            granaryDto.setSmog(smogService.getNow(c.getNumber()).getSmog());
            granaryDto.setTemperature(temperatureService.getNow(c.getNumber()).getTemperature());
            granaryDtoList.add(granaryDto);
        });
        return granaryDtoList;

    }
}
